/**
 * 
 */
package edu.erpan.util.entityManager;

import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import edu.erpan.util.entityManager.exceptions.IdNotFoundException;
import edu.erpan.util.entityManager.exceptions.PersistException;
import edu.erpan.util.entityManager.exceptions.QueryException;

/**
 * @author Jeison
 * @param <E>
 *
 */
public class GenericEntityManager<E extends DefaultEntity> {

	@Resource
	private UserTransaction userTransaction;
	@PersistenceContext(unitName="ERPanJPA")  
    private EntityManager entityManager;
	private Class<E> clase;

	/**
	 * 
	 */
	public GenericEntityManager(Class<E> clase) {
		// w
		this.clase=clase;
	}
	
    public void saveEntity(E entity) throws PersistException {
    	try{
    		getEntityManager().merge(entity);
    		
    	}catch (Exception e) {
    		throw new PersistException(e);
		}
    }
    
    @SuppressWarnings("unchecked")
	public E findEntity(E entity) throws IdNotFoundException, QueryException {
        try{ 

        	DefaultEntity p = getEntityManager().find(entity.getClass(), entity.getEntityId());

        	return (E) p;
        }catch (IdNotFoundException e) {
        	throw e;
        }catch (Exception e) {
        	throw new QueryException(e);
        }
        
    }
    
	public void mergeEntity(E entity)
			throws QueryException {
		try{
			this.getEntityManager().merge(entity);
		}catch (Exception e) {
    		throw new QueryException(e);
		}
		
	}
	
	public void deleteEntity(E entity)
			throws QueryException,IdNotFoundException {
		try{
			entity=this.getEntityManager().getReference(clase, entity.getEntityId());
			this.getEntityManager().remove(entity);
		}catch (Exception e) {
    		throw new QueryException(e);
		}
		
	}
    
    @SuppressWarnings("unchecked")
    public List<E> retrieveAllEntities() throws QueryException {

        String q = "SELECT p from " + clase.getName() + " p";
        try{
	        Query query = getEntityManager().createQuery(q);
	        List<E> entities = query.getResultList();
	        
	        return entities;
        }catch (Exception e) {
        	throw new QueryException(e);
        }
        
    }

	protected UserTransaction getUserTransaction() {
		return userTransaction;
	}
	
	protected EntityManager getEntityManager(){
		return entityManager;
    	
    }
}
